package com.macbulldev.poc.testgin.controller;

import java.util.Date;
import java.util.Set;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.log4j.Logger;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.macbulldev.poc.testgin.domain.AppUser;
import com.macbulldev.poc.testgin.domain.EventLog;
import com.macbulldev.poc.testgin.domain.PolicyForm;
import com.macbulldev.poc.testgin.domain.Rate;
import com.macbulldev.poc.testgin.domain.Scenario;
import com.macbulldev.poc.testgin.domain.StateOrProvince;
import com.macbulldev.poc.testgin.domain.Tier;
import com.macbulldev.poc.testgin.domain.TrialGroup;
import com.macbulldev.poc.testgin.domain.Underwriter;
import com.macbulldev.poc.testgin.service.WebappUtils;


@org.springframework.roo.addon.web.mvc.controller.RooWebScaffold(path = "rate", automaticallyMaintainView = false, formBackingObject = com.macbulldev.poc.testgin.domain.Rate.class)
@org.springframework.web.bind.annotation.RequestMapping("/rate/**")
@org.springframework.stereotype.Controller
public class RateController {
	
	
	private static final Logger LOGGER = Logger.getLogger(Rate.class);
	
	@RequestMapping(value = "/rate/list", method = RequestMethod.GET)    
    public String renderRateList(@RequestParam(value = "pageNumber", required = false) Integer page, ModelMap modelMap) {    

		
		int sizeNo = 20;           
        int pageNumber= page == null ? 0 : page;
        
        modelMap.addAttribute("rates",Rate.findRateEntries(pageNumber*sizeNo, sizeNo));            
        Long count = Rate.countRates();
        modelMap.addAttribute("maxPageNumber", (Long)(count/sizeNo));
        
        modelMap.addAttribute("stateorprovinces",StateOrProvince.findAllStateOrProvinces());
        
        return "rate/list";        
    }
	
	@RequestMapping(value = "/rate/filter", method = RequestMethod.GET)    
    public String renderPolicyFormList(@RequestParam(value = "stateOrProvince", required = false) Long stateOrProvinceId,ModelMap modelMap) {    
		
		int sizeNo = 100;
		Integer page = null;
        int pageNumber= page == null ? 0 : page;
        
        if(stateOrProvinceId == 0)
        {
        	 sizeNo = 20;
        	 modelMap.addAttribute("stateorprovince",stateOrProvinceId);
        	 modelMap.addAttribute("stateorprovinces",StateOrProvince.findAllStateOrProvinces());
             modelMap.addAttribute("rates",Rate.findRateEntries(pageNumber*sizeNo, sizeNo));            
             Long count = Rate.countRates();
             modelMap.addAttribute("maxPageNumber", (Long)(count/sizeNo));
        }
        else
        {
        	modelMap.addAttribute("stateorprovince",stateOrProvinceId);
        	modelMap.addAttribute("stateorprovinces",StateOrProvince.findAllStateOrProvinces());
        	Set<Rate> rates = null;
        	rates = StateOrProvince.findStateOrProvince(stateOrProvinceId).getRates();
            modelMap.addAttribute("rates",rates);
            Long count = Long.valueOf(rates.size());
            modelMap.addAttribute("maxPageNumber", (Long)(count/sizeNo));
        }
        
        return "rate/list";        
    }
	
	@RequestMapping(value = "/rate/create_wizard", method = RequestMethod.GET)    
    public String renderRateCreateWizard(ModelMap modelMap) {    
        modelMap.addAttribute("rate", new Rate());        
        modelMap.addAttribute("stateorprovinces", StateOrProvince.findAllStateOrProvinces());        
        modelMap.addAttribute("tiers", Tier.findAllTiers());        
        modelMap.addAttribute("trialgroups", TrialGroup.findAllTrialGroups());        
        modelMap.addAttribute("underwriters", Underwriter.findAllUnderwriters());        
        return "rate/create_wizard";        
    }
	@RequestMapping(value = "/rate/ajax/{name}/{stateorprovinceId}", method = RequestMethod.GET)      
    public String processRateCreateWizard(@PathVariable("name") String name,
    									@PathVariable("stateorprovinceId") Long stateOrProvinceId,
    									ModelMap modelMap,
    									HttpSession session
    									) 
	{    
        
		/* first Check to See if that Name already exists for that State */
		
		Rate rate = null;
		rate = rate.getByRateNameAndStateOrProvince(name, stateOrProvinceId);
		String retMsg = "";
		
		if(rate == null)
		{
			
			
			rate = new Rate();
			rate.setName(name);
			rate.setStateOrProvince(StateOrProvince.findStateOrProvince(stateOrProvinceId));
			rate.setCreateTs(new Date());
			rate.setUpdateTs(new Date());
		
			AppUser sessionUser = WebappUtils.getAuthenticationObject(session);
        
        	rate.setCreateUsername(sessionUser.getName());
        	rate.setUpdateUsername(sessionUser.getName());
			 
			rate.persist();
			retMsg =  ""+rate.getByRateNameAndStateOrProvince(rate.getName(), rate.getStateOrProvince().getId()).getId();
			
			
			EventLog log = new EventLog();
	    	log.setCreateTs(new Date());
	    	log.setCreateUsername(sessionUser.getName());

	    	log.setObjectClass(Rate.class.getSimpleName());
	    	log.setOperation("Rate "+ rate.getName()+" Created");
	    	log.persist();
			
			
		}
		else
		{
			retMsg = "Sorry this name already exists for this state. Please Choose Another One";
		}
		
		
		LOGGER.error("Return Message:   "+retMsg);
		
		modelMap.addAttribute("msg", retMsg);  
		return "rate/ajax_success"; 

    }
	
	
	
	@RequestMapping(value = "/rate/update/ajax", method = RequestMethod.POST)      
    public String processRateCreateWizard(@Valid Rate rate, @RequestParam(value = "rateid", required = false) Long rateid, @RequestParam(value = "state", required = false) Long stateid, ModelMap modelMap,HttpSession session) 
	{    
        
		LOGGER.error("Update Rate");
        
		LOGGER.error(rate.getName()+":"+stateid+":"+rateid);
		String retMsg = "";
		
        Rate current = Rate.findRate(rateid);
        current.setName(rate.getName());
        current.setStateOrProvince(StateOrProvince.findStateOrProvince(stateid));
        
        AppUser sessionUser = WebappUtils.getAuthenticationObject(session);
        current.setUpdateUsername(sessionUser.getName());
        current.setUpdateTs(new Date());

        current.merge();    
        
        EventLog log = new EventLog();
    	log.setCreateTs(new Date());
    	log.setCreateUsername(sessionUser.getName());

    	log.setObjectClass(Rate.class.getSimpleName());
    	log.setOperation("Rate "+ current.getName()+" updated");
    	log.persist();
        

        retMsg =  ""+rateid;  
		return "rate/ajax_success";
    }
	
	

	@RequestMapping(value = "/rate", method = RequestMethod.POST)    
    public String create(@Valid Rate rate, BindingResult result, ModelMap modelMap,HttpSession session) {    
        if (rate == null) throw new IllegalArgumentException("A rate is required");        
        if (result.hasErrors()) {        
            modelMap.addAttribute("rate", rate);            
            modelMap.addAttribute("stateorprovinces", StateOrProvince.findAllStateOrProvinces());            
            modelMap.addAttribute("tiers", Tier.findAllTiers());            
            modelMap.addAttribute("trialgroups", TrialGroup.findAllTrialGroups());            
            modelMap.addAttribute("underwriters", Underwriter.findAllUnderwriters());            
            return "rate/create";            
        }
        
        AppUser sessionUser = WebappUtils.getAuthenticationObject(session);
        rate.setCreateUsername(sessionUser.getName());
        rate.setUpdateUsername(sessionUser.getName());
        rate.setCreateTs(new Date());
        rate.setUpdateTs(new Date());
        
        rate.persist();
        
        EventLog log = new EventLog();
    	log.setCreateTs(new Date());
    	log.setCreateUsername(sessionUser.getName());

    	log.setObjectClass(Rate.class.getSimpleName());
    	log.setOperation("Rate "+ rate.getName()+" Created");
    	log.persist();
        
        
        return "redirect:/rate/" + rate.getId();        
    }

	@RequestMapping(value = "/rate/form", method = RequestMethod.GET)    
    public String createForm(ModelMap modelMap) {    
        modelMap.addAttribute("rate", new Rate());        
        modelMap.addAttribute("stateorprovinces", StateOrProvince.findAllStateOrProvinces());        
        modelMap.addAttribute("tiers", Tier.findAllTiers());        
        modelMap.addAttribute("trialgroups", TrialGroup.findAllTrialGroups());        
        modelMap.addAttribute("underwriters", Underwriter.findAllUnderwriters());        
        return "rate/create";        
    }

	@RequestMapping(value = "/rate/{id}", method = RequestMethod.GET)    
    public String show(@PathVariable("id") Long id, ModelMap modelMap) {    
        if (id == null) throw new IllegalArgumentException("An Identifier is required");        
        modelMap.addAttribute("rate", Rate.findRate(id));
        modelMap.addAttribute("tiers",Tier.findTiersByRate(id));
        return "rate/show";        
    }

	@RequestMapping(value = "/rate", method = RequestMethod.GET)    
    public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, ModelMap modelMap) {    
        if (page != null || size != null) {        
            int sizeNo = size == null ? 10 : size.intValue();            
            modelMap.addAttribute("rates", Rate.findRateEntries(page == null ? 0 : (page.intValue() - 1) * sizeNo, sizeNo));            
            float nrOfPages = (float) Rate.countRates() / sizeNo;            
            modelMap.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));            
        } else {        
            modelMap.addAttribute("rates", Rate.findAllRates());            
        }        
        return "rate/list";        
    }

	@RequestMapping(method = RequestMethod.PUT)    
    public String update(@Valid Rate rate, BindingResult result, ModelMap modelMap,HttpSession session) {    
        if (rate == null) throw new IllegalArgumentException("A rate is required");        
        if (result.hasErrors()) {        
            modelMap.addAttribute("rate", rate);            
            modelMap.addAttribute("stateorprovinces", StateOrProvince.findAllStateOrProvinces());            
            modelMap.addAttribute("tiers", Tier.findAllTiers());            
            modelMap.addAttribute("trialgroups", TrialGroup.findAllTrialGroups());            
            modelMap.addAttribute("underwriters", Underwriter.findAllUnderwriters());            
            return "rate/update";            
        }  
        
        Rate current = rate.findRate(rate.getId());
        
        AppUser sessionUser = WebappUtils.getAuthenticationObject(session);
        rate.setCreateUsername(current.getCreateUsername());
        rate.setUpdateUsername(sessionUser.getName());
        rate.setCreateTs(current.getCreateTs());
        rate.setUpdateTs(new Date());
        
        EventLog log = new EventLog();
    	log.setCreateTs(new Date());
    	log.setCreateUsername(sessionUser.getName());

    	log.setObjectClass(Rate.class.getSimpleName());
    	log.setOperation("Rate "+ rate.getName()+" Updated");
    	log.persist();
        
        
        rate.merge();        
        return "redirect:/rate/" + rate.getId();        
    }

	@RequestMapping(value = "/rate/{id}", method = RequestMethod.DELETE)    
    public String delete(@PathVariable("id") Long id, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size) {    
        if (id == null) throw new IllegalArgumentException("An Identifier is required");        
        Rate.findRate(id).remove();        
        return "redirect:/rate?page=" + ((page == null) ? "1" : page.toString()) + "&size=" + ((size == null) ? "10" : size.toString());        
    }
    
	
	@RequestMapping(value = "/rate/{id}/form/update", method = RequestMethod.GET)    
    public String renderRateUpdateForm(@PathVariable("id") Long id, ModelMap modelMap) {    
        if (id == null) throw new IllegalArgumentException("An Identifier is required");        
        modelMap.addAttribute("rate", Rate.findRate(id));
        modelMap.addAttribute("stateorprovinces", StateOrProvince.findAllStateOrProvinces());        
        modelMap.addAttribute("tiers", Tier.findTiersByRate(id));        
        modelMap.addAttribute("trialgroups", TrialGroup.findAllTrialGroups());        
        modelMap.addAttribute("underwriters", Underwriter.findAllUnderwriters());        
        return "rate/update_wizard";        
    }

	@RequestMapping(value = "/rate/{id}/form", method = RequestMethod.GET)    
    public String updateForm(@PathVariable("id") Long id, ModelMap modelMap) {    
        if (id == null) throw new IllegalArgumentException("An Identifier is required");        
        modelMap.addAttribute("rate", Rate.findRate(id));        
        modelMap.addAttribute("stateorprovinces", StateOrProvince.findAllStateOrProvinces());        
        modelMap.addAttribute("tiers", Tier.findAllTiers());        
        modelMap.addAttribute("trialgroups", TrialGroup.findAllTrialGroups());        
        modelMap.addAttribute("underwriters", Underwriter.findAllUnderwriters());        
        return "rate/update";        
    }
}
